<template>
  <div
    class="vk-collapse-item"
    :class="{
      'is-disabled': disabled,
    }"
  >
    <div
      class="vk-collapse-item__header"
      :class="{
        'is-disabled': disabled,
        'is-active': isActive,
      }"
      :id="`item-header-${name}`"
      @click="handleClick"
    >
      <slot name="title">{{ title }}</slot>
      <Icon icon="angle-right" class="header-angle"></Icon>
    </div>
    <transition name="slide" v-on="transitionEvents">
      <div class="vk-collapse-item__wrapper" v-show="isActive">
        <div class="vk-collapse-item__content" :id="`item-header-${name}`">
          <slot></slot>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import Icon from "../Icon/Icon.vue";
import type { CollapseItemProps } from "./types";
import { CollapseContextKey } from "./types";
import { defineProps, defineOptions, inject, computed } from "vue";

defineOptions({
  name: "VkCollapseItem",
});
const props = defineProps<CollapseItemProps>();

const CollapseContext = inject(CollapseContextKey);

// 包含：展开，不包含：关闭
const isActive = computed(() => {
  return CollapseContext?.activeNames.value.includes(props.name);
});

const handleClick = () => {
  if (props.disabled) {
    return;
  }
  CollapseContext?.handleItemClick(props.name);
};

// 定义一个方法的对象，就可以不用在 transition标签上一个个写出来了
//   @before-enter="onBeforeEnter"
//   @enter="onEnter"
//   @after-enter="onAfterEnter"
//   @before-leave="onBeforeLeave"
//   @leave="onLeave"
//   @after-leave="onAfterLeave"
const transitionEvents: Record<string, (el: HTMLElement) => void> = {
  beforeEnter(el) {
    el.style.height = "0px";
    el.style.overflow = "hidden";
  },
  enter(el) {
    el.style.height = `${el.scrollHeight}px`;
  },
  afterEnter(el) {
    el.style.height = "";
    el.style.overflow = "";
  },
  beforeLeave(el) {
    el.style.height = `${el.scrollHeight}px`;
    el.style.overflow = "hidden";
  },
  leave(el) {
    el.style.height = `0px`;
  },
  afterLeave(el) {
    el.style.height = "";
    el.style.overflow = "";
  },
};
</script>

<style scoped>
.vk-collapse-item__header {
  font-size: 30px;
}
</style>
